package cn.bearspark.common.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 自旋锁
 *
 * @author f
 */
public class SpinLock implements Lock {

    private final AtomicBoolean lock = new AtomicBoolean(false);

    @Override
    public void lock() {
        while (!lock.compareAndSet(false, true)) {
            try {
                // 每次获取不到锁时休眠 10ms，防止锁大量消耗系统性能
                TimeUnit.MILLISECONDS.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void unlock() {
        lock.set(false);
    }
}
